﻿using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.ComponentModel;
using System.Text;

namespace PmSoft;

public static class HttpRequestExtensions
{
    /// <summary>
    /// 是否为Ajax请求
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public static bool IsAjaxRequest(this HttpRequest request)
    {
        if (request == null)
            throw new ArgumentNullException("request");

        if (request.Headers != null)
            return request.Headers["X-Requested-With"] == "XMLHttpRequest";
        return false;
    }

    /// <summary>
    /// 是否为POST请求
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public static bool IsPost(this HttpRequest request)
    {
        if (request == null)
            throw new ArgumentNullException("request");
        if (request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
            return true;
        return false;
    }


    /// <summary>
    /// 获取请求参数(POST/GET)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="request"></param>
    /// <param name="key"></param>
    /// <param name="defaultValue"></param>
    /// <returns></returns>
    public static T GetParams<T>(this HttpRequest request, string key, T defaultValue = default(T))
    {
        string value = string.Empty;

        if (request.Query.ContainsKey(key))
            value = request.Query[key];

        if (string.IsNullOrEmpty(value) && request.HasFormContentType && request.Form.ContainsKey(key))
            value = request.Form[key];

        if (string.IsNullOrEmpty(value))
            return defaultValue;

        Type tType = typeof(T);
        if (tType.IsGenericType && tType.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            return (T)TypeDescriptor.GetConverter(Nullable.GetUnderlyingType(tType)).ConvertFrom(value);
        }
        else if (tType.IsEnum)
        {
            return (T)Enum.Parse(tType, value);
        }
        else
        {
            try
            {
                return (T)Convert.ChangeType(value, tType);
            }
            catch
            {
                return defaultValue;
            }
        }

    }

    /// <summary>
    /// 获取当前请求完整的Url地址
    /// </summary>
    /// <returns></returns>
    public static string GetCompleteUrl(this HttpRequest request)
    {
        return new StringBuilder()
             .Append(request.Scheme)
             .Append("://")
             .Append(request.Host)
             .Append(request.PathBase)
             .Append(request.Path)
             .Append(request.QueryString)
             .ToString();
    }
}
